"""处理是否显示添加删除编辑按钮的公共类"""
from django.conf import settings
from django.utils.safestring import mark_safe

from stark.service.v1 import StarkHandler


class PermissionHandler(StarkHandler):
    # 是否显示添加按钮
    def get_add_btn(self, request, *args, **kwargs):
        """粒度控制，判断用户是否有添加权限"""

        url_name = self.get_add_url_name
        if url_name not in request.session.get(settings.PERMISSION_SESSION_KEY):
            return None
        if self.has_add_btn:
            add_url = self.reverse_add_url(*args, **kwargs)
            return '<a href="%s" style="margin-left:10px" class="btn btn-primary">添加</a>' % add_url
        return None

    # 是否显示编辑或删除按钮
    def get_field_name_list(self, request, *args, **kwargs):
        # 为当前也显示的列进行扩展需求
        permissions_dict = request.session.get(settings.PERMISSION_SESSION_KEY)
        value = []
        if self.field_name_list:
            value.extend(self.field_name_list)
            if self.get_edit_url_name in permissions_dict and self.get_del_url_name in permissions_dict:
                value.append(type(self).display_edit_del)  # 添加默认显示的操作字段： 编辑和删除
            elif self.get_edit_url_name in permissions_dict:
                value.append(type(self).display_edit)
            elif self.get_del_url_name in permissions_dict:
                value.append(type(self).display_del)
        return value